package com.telnetnz.ticketdesk.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.telnetnz.ticketdesk.bean.Template;
import com.telnetnz.ticketdesk.common.config.SpringContext;
import com.telnetnz.ticketdesk.dao.entity.TemplateEntity;
import com.telnetnz.ticketdesk.dao.wrapper.TemplateWrap;

public class TemplateService
{
	public static final String[] TYPES = {
		"Freemarker: newsletter"
	};
	public static final int TYPE_NEWSLETTER = 0;

	public static void addTemplate(Template template)
	{
		if (template == null) return;
		template.setUpdateTime(new Date());
		getWrap().insert(template.toEntity());
	}

	public static void updateTemplate(Template template)
	{
		if (template == null) return;
		template.setUpdateTime(new Date());
		getWrap().update(template.toEntity());
	}

	public static Template getTemplate(int id)
	{
		TemplateEntity entity = getWrap().select(id);
		return Template.adapt(entity);
	}

	public static List<Template> getAllTemplates()
	{
		List<TemplateEntity> entities = getWrap().selectAll();
		return adaptList(entities);
	}

	public static List<Template> getTemplatesByType(int type)
	{
		List<TemplateEntity> entities = getWrap().selectByType(type);
		return adaptList(entities);
	}

	private static List<Template> adaptList(List<TemplateEntity> entities)
	{
		List<Template> beans = new ArrayList<Template>();
		if (entities != null && entities.size() > 0)
		{
			for (TemplateEntity entity: entities)
			{
				Template bean = Template.adapt(entity);
				if (bean != null)
					beans.add(bean);
			}
		}
		return beans;
	}

	private static TemplateWrap getWrap()
	{
		return SpringContext.getTemplateWrap();
	}
}
